package org.example.medicalstaff.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.example.his.common.api.CommonResponse;
import org.example.medicalstaff.entity.*;
import org.example.medicalstaff.mapper.*;
import org.example.medicalstaff.service.PrescriptionService;
import org.example.medicalstaff.utils.DateStringFormat;
import org.example.medicalstaff.vo.DrugAndPreDetailed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PrescriptionServiceImpl implements PrescriptionService {

    @Autowired
    private PrescriptionMapper prescriptionMapper;
    @Autowired
    private PrescriptionDetailedMapper prescriptionDetailedMapper;
    @Autowired
    private Prescripition prescripition;
    @Autowired
    private PrescriptionDetailed prescriptionDetailed;
    @Autowired
    DrugsTemplateMapper drugsTemplateMapper;
    @Autowired
    DrugsDetailedMapper drugsDetailedMapper;
    @Autowired
    DrugsMapper drugsMapper;

    /**
     * CH AREA
     */

    /**
     * API1 暂存开立处方
     */
    public CommonResponse<Prescripition> tem_store_pres(
            int MedicalID,
            int RegistID,
            int UserID,
            String PrescriptionName
    ){
        //设置当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
        String pattern = "yyyy-MM-dd HH:mm:ss";
        Date date = DateStringFormat.parseDateTimeString(formattedDateTime,pattern);
        Prescripition prescripition = new Prescripition();
        prescripition.setMedicalID(MedicalID);
        prescripition.setRegistID(RegistID);
        prescripition.setUserID(UserID);
        prescripition.setPrescriptionName(PrescriptionName);
        prescripition.setPrescriptionTime(date);
        prescripition.setPrescriptionState(1);
        int result = prescriptionMapper.insert(prescripition);
        if (result == 0){
            return CommonResponse.createForError("暂存开立处方失败，无法插入新记录");
        }else{
            return CommonResponse.createForSuccess("暂存开立处方成功",prescripition);
        }
    }

    /**
     * API2 根据药品处方获取药品明细
     */
    public CommonResponse<List<DrugAndPreDetailed>> getDetailByPre(
            int MedicalID,
            int RegistID,
            int UserID,
            String PrescriptionName
    ){
        List<DrugAndPreDetailed> drugAndPreDetaileds = new ArrayList<>();
        //根据这四个属性获取药品处方
        QueryWrapper<Prescripition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MedicalID",MedicalID);
        queryWrapper.eq("RegistID",RegistID);
        queryWrapper.eq("UserID",UserID);
        queryWrapper.eq("PrescriptionName",PrescriptionName);
        prescripition = prescriptionMapper.selectOne(queryWrapper);
        int PreID = prescripition.getID();
        //根据ID获取药品明细的LIST
        QueryWrapper<PrescriptionDetailed> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("PrescriptionID",PreID);
        List<PrescriptionDetailed> prescriptionDetailedList = prescriptionDetailedMapper.selectList(queryWrapper2);
        //变量list获取drugs的数据
        for (int i = 0; i < prescriptionDetailedList.size(); i++) {
            DrugAndPreDetailed drugAndPreDetailed = new DrugAndPreDetailed();
            int DrugsID = prescriptionDetailedList.get(i).getDrugsID();
            QueryWrapper<Drugs> drugsQueryWrapper = new QueryWrapper<>();
            drugsQueryWrapper.eq("ID",DrugsID);
            Drugs drug = drugsMapper.selectOne(drugsQueryWrapper);
            if (drug == null){
                return CommonResponse.createForError("获取药品失败");
            }
            drugAndPreDetailed.setDrugsFormat(drug.getDrugsFormat());
            drugAndPreDetailed.setDrugsName(drug.getDrugsName());
            drugAndPreDetailed.setDrugsPrice(drug.getDrugsPrice());
            drugAndPreDetailed.setDrugsUsage(prescriptionDetailedList.get(i).getDrugsUsage());
            drugAndPreDetailed.setFrequency(prescriptionDetailedList.get(i).getFrequency());
            drugAndPreDetailed.setDosage(prescriptionDetailedList.get(i).getDosage());
            drugAndPreDetailed.setAmount(prescriptionDetailedList.get(i).getAmount());
            drugAndPreDetaileds.add(drugAndPreDetailed);
        }
        if (prescriptionDetailedList != null){
            return CommonResponse.createForSuccess("获取药品明细成功",drugAndPreDetaileds);
        }else{
            return CommonResponse.createForError("获取药品明细失败");
        }
    }

    /**
     * API3 修改暂存开立处方
     */
    public CommonResponse<String> modify_tem(
            int MedicalID,
            int RegistID,
            int UserID,
            String PrescriptionName
    ){
//        //这里要把时间转换为Date再存入
//        //设置时间格式
//        String pattern = "yyyy-MM-dd HH:mm:ss";
//        Date date = DateStringFormat.parseDateTimeString(PrescriptionTime,pattern);
//        //前面三个加第五个能确定，我觉得时间是不能改的，名称是可以修改的。
        UpdateWrapper<Prescripition> updateWrapper = new UpdateWrapper();
        updateWrapper.set("PrescriptionState",2)
                .eq("MedicalID",MedicalID)
                .eq("RegistID",RegistID)
                .eq("UserID",UserID);
        int result = prescriptionMapper.update(null,updateWrapper);
        if (result == 0){
            return CommonResponse.createForError("修改暂存开立处方失败，属性不匹配");
        }else{
            return CommonResponse.createForSuccess("修改暂存开立处方成功");
        }
    }

    /**
     * API4 删除暂存开立处方
     */
    public CommonResponse<String> del_tem(
            int MedicalID,
            int RegistID,
            int UserID,
            String PrescriptionName
    ){
        QueryWrapper<Prescripition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MedicalID",MedicalID);
        queryWrapper.eq("RegistID",RegistID);
        queryWrapper.eq("UserID",UserID);
        queryWrapper.eq("PrescriptionName",PrescriptionName);
        //先判断是否是暂存状态
        prescripition = prescriptionMapper.selectOne(queryWrapper);
        if (prescripition.getPrescriptionState()!=1){
            return CommonResponse.createForError("删除失败，不是暂存状态");
        }
        //然后删除明细
        int preID = prescripition.getID();
        QueryWrapper<PrescriptionDetailed> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("PrescriptionID",preID);
        prescriptionDetailedMapper.delete(queryWrapper1);
        //然后删除处方
        int result = prescriptionMapper.delete(queryWrapper);
        if (result == 0){
            return CommonResponse.createForError("删除失败，属性不匹配");
        }else{
            return CommonResponse.createForSuccess("删除成功");
        }
    }

    /**
     * API5 暂存处方增加药品
     */
    public CommonResponse<String> addItem(
            int PrescriptionID,
            int DrugsID,
            String DrugsUsage,
            String Dosage,
            String Frequency,
            int Amount
    ){
        PrescriptionDetailed prescriptionDetailed = new PrescriptionDetailed();
        prescriptionDetailed.setPrescriptionID(PrescriptionID);
        prescriptionDetailed.setDrugsID(DrugsID);
        prescriptionDetailed.setDrugsUsage(DrugsUsage);
        prescriptionDetailed.setDosage(Dosage);
        prescriptionDetailed.setFrequency(Frequency);
        prescriptionDetailed.setAmount(BigDecimal.valueOf(Amount));
        prescriptionDetailed.setState(1);
        int result = prescriptionDetailedMapper.insert(prescriptionDetailed);
        if (result == 0){
            return CommonResponse.createForError("增加药品失败，无法插入记录");
        }else{
            return CommonResponse.createForSuccess("增加药品成功");
        }
    }

    /**
     * API6 暂存处方删除药品
     */
    public CommonResponse<String> del_m(
            int PrescriptionID,String DrugsName,String DrugsFormat,BigDecimal DrugsPrice
    ){
        QueryWrapper<Drugs> drugsQueryWrapper = new QueryWrapper<>();
        drugsQueryWrapper.eq("DrugsName",DrugsName).eq("DrugsFormat",DrugsFormat).eq("DrugsPrice",DrugsPrice);
        Drugs drugs = drugsMapper.selectOne(drugsQueryWrapper);
        int DrugsID = drugs.getID();
        QueryWrapper<PrescriptionDetailed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PrescriptionID",PrescriptionID);
        queryWrapper.eq("DrugsID",DrugsID);
        int result = prescriptionDetailedMapper.delete(queryWrapper);
        if (result == 0){
            return CommonResponse.createForError("暂存处方删除药品失败");
        }else{
            return CommonResponse.createForSuccess("暂存处方删除药品成功");
        }
    }


    /**
     * API7 获取当前状态的所有处方
     */
    public CommonResponse<List<Prescripition>> get_pre(
            int MedicalID,
            int RegistID,
            int UserID
    ){
        QueryWrapper<Prescripition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MedicalID",MedicalID);
        queryWrapper.eq("RegistID",RegistID);
        queryWrapper.eq("UserID",UserID);
        List<Prescripition> Prescripitions = new ArrayList<>();
        Prescripitions = prescriptionMapper.selectList(queryWrapper);
        if (Prescripitions != null){
            return CommonResponse.createForSuccess("获取成功",Prescripitions);
        }else{
            return CommonResponse.createForError("获取失败");
        }
    }


    /**
     * ZCJ AREA
     */
    /**
     * API 新增处方使用组套药品
     */
    public CommonResponse<Prescripition> prescripiton_managePrescripition_add(
            int ID,
            int MedicalID,
            int RegistID,
            int UserID,
            BigDecimal Amount
    ){
        QueryWrapper<DrugsTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID",ID);
        DrugsTemplate drugsTemplate1 = drugsTemplateMapper.selectOne(queryWrapper);
        String PrescriptionName=drugsTemplate1.getName();
        Date CreationTime=drugsTemplate1.getCreationTime();

        QueryWrapper<DrugsDetailed> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("DrugsTempID",ID);
        List<DrugsDetailed> list = drugsDetailedMapper.selectList(queryWrapper1);
        //再把list中的加到处方明细表中去。。。



        Prescripition prescripition1=new Prescripition();
        prescripition1.setUserID(UserID);
        prescripition1.setMedicalID(MedicalID);
        prescripition1.setRegistID(RegistID);
        prescripition1.setPrescriptionName(PrescriptionName);


        prescripition1.setPrescriptionTime(CreationTime);

        int result=prescriptionMapper.insert(prescripition1);
        int flag=1;
        if(result==1)//这个是说在prescription里增加成功
        {

            for(int i=0;i<list.size();i++) {
                PrescriptionDetailed prescriptionDetailed1 = new PrescriptionDetailed();
                prescriptionDetailed1.setPrescriptionID(prescripition1.getID());
                prescriptionDetailed1.setDrugsID(list.get(i).getDrugsID());
                prescriptionDetailed1.setDrugsUsage(list.get(i).getDrugsUsage());
                prescriptionDetailed1.setDosage(list.get(i).getDosage());
                prescriptionDetailed1.setFrequency(list.get(i).getFrequency());
                prescriptionDetailed1.setAmount(Amount);
                prescriptionDetailed1.setState(0);
                int result2=prescriptionDetailedMapper.insert(prescriptionDetailed1);
                if(result2==0)flag=0;//这个是说如果有某一次在prescriptionDetail添加失败，总的就是失败的
            }
        }

        if(result==1&&flag==1)
            return CommonResponse.createForSuccess("新增成功",prescripition1);
        else
            return  CommonResponse.createForError(1,"新增失败");

    }

    @Override
    public CommonResponse<Prescripition> prescripiton_managePrescripition_update(
            int MedicalID,
            int RegistID,
            int UserID,
            String PrescriptionName) {

        QueryWrapper<Prescripition> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("MedicalID",MedicalID);
        queryWrapper.eq("RegistID",RegistID);
        queryWrapper.eq("UserID",UserID);
        queryWrapper.like("PrescriptionName",PrescriptionName);
        Prescripition prescripition1=prescriptionMapper.selectOne(queryWrapper);
        prescripition1.setPrescriptionState(2);
        int result=prescriptionMapper.update(prescripition1,queryWrapper);
        if(result==1)
            return CommonResponse.createForSuccess("修改成功",prescripition1);
        else
            return CommonResponse.createForError(1,"修改失败");

    }

}
